package cn.lsj.lock.aop;


import cn.lsj.lock.annotation.GlobalLock;
import cn.lsj.lock.core.ReentrantLock;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.ApplicationContext;

import javax.annotation.Resource;
import java.lang.reflect.Method;

@Aspect
public class GlobalLockAspect {

    @Resource
    private ApplicationContext applicationContext;


    @Pointcut("@annotation(cn.lsj.lock.annotation.GlobalLock)")
    public void globalLock() {
    }

    @Around("globalLock()")
    public Object applyGlobalLock(ProceedingJoinPoint joinPoint) throws Throwable {

        String lockName = getLockName(joinPoint);
        ReentrantLock lock = applicationContext.getBean(lockName, ReentrantLock.class);

        Object result;
        try {
            lock.lock();
            result = joinPoint.proceed();
        } finally {
            lock.unlock();
        }
        return result;
    }

    private String getLockName(ProceedingJoinPoint joinPoint) throws NoSuchMethodException {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        GlobalLock globalLock = method.getAnnotation(GlobalLock.class);
        return globalLock.value();
    }

}
